//用户状态模块

//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/system/user/user'
//引入类型
import type { LoginFormData, LoginResponseData, UserInfoResponseData } from '@/api/system/user/type'
//引入本地存储
import { setToken, getToken, clearToken } from '@/utils/localStorage'
import { defineStore } from 'pinia'

import type { UserState } from './types/type'

//引入常量路由
import { constantRoutes } from '@/router/routes'

const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: getToken() || '',
      menuRoutes: constantRoutes,
      username: '', //用户名
      avatar: '', //用户头像
    }
  },
  getters: {},
  actions: {
    //用户登录的方法
    async userLogin(data: LoginFormData) {
      //console.log(data)
      //登录请求
      let result: LoginResponseData = await reqLogin(data)
      console.log('调用真实登录接口', result)
      //登录请求:成功->保存token
      if (result.code === 200) {
        //pinia仓库存储一下token，pinia|vuex存储数据本质上利用的是js对象
        this.token = result.data as string
        //本地存储持久化存储一份
        setToken(result.data as string)
        //登录成功返回true
        return 'OK'
      } else {
        //登录请求:失败->提示错误信息
        return Promise.reject(new Error(result.message))
      }
    },
    //获取用户信息的方法
    async userInfo() {
      //获取用户信息进行仓储存储，包括用户头像和名称
      let user: UserInfoResponseData = await reqUserInfo()
      console.log('调用真实获取用户信息接口', user)
      if (user.code === 200) {
        this.username = user.data.name
        this.avatar = user.data.avatar
        return 'OK'
      } else {
        return Promise.reject(user.message)
      }
    },
    //用户退出系统
    async userLogout() {
      //调用退出接口
      let result = await reqLogout()
      console.log('调用真实退出接口', result)
      if (result.code === 200) {
        //清除pinia仓库中保存的token及用户信息
        this.token = ''
        this.username = ''
        this.avatar = ''
        //清除本地存储的token
        clearToken()
        return 'OK'
      } else {
        return Promise.reject(result.message)
      }
    },
  },
})

export default useUserStore
